package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    //数据库的约束错误信息
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handlerSqlConstraintException(SQLIntegrityConstraintViolationException ex){

        //打印异常信息
        String message = ex.getMessage();
        //System.out.println("message = " + message);
        log.info("异常信息为:{}"+message);
        String replace = message.split(" ")[2].replace("'", "");

        return R.error("账号"+replace+"已存在");
    }

    //自定义异常处理
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        log.error(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
